package com.yixing.demo.controller;

import com.yixing.demo.constants.Constants;
import com.yixing.demo.model.Result;
import com.yixing.demo.model.User;
import com.yixing.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @RequestMapping("/login")
    public Result<User> login(String username, String password, HttpSession session) {
       if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
           return new Result<>(-1, "用户名或密码错误！", null);
       }
        User userInfo = userService.login(username);
       if(userInfo == null) {
           return new Result<>(-1, "用户名或密码错误！", null);
       }else {
           if(bCryptPasswordEncoder.matches(password, userInfo.getPassword())) {
               session.setAttribute(Constants.USER_SESSION, userInfo);
               userInfo.setPassword("");
               return new Result<>(1, "登录成功！", userInfo);
           }else {
               return new Result<>(-1, "用户名或密码错误！", null);
           }
       }
    }
}
